﻿using System;
using Com.Lancetinc.Evs.Events;
using Com.Lancetinc.Evs.Helpers;
using Com.Lancetinc.Evs.Windows;
using NLog;

namespace Com.Lancetinc.Evs.Controls
{
    /// <summary>
    /// 医师信息设置
    /// </summary>
    public partial class DoctorSettingUserControl : ISettingControl
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public DoctorSettingUserControl()
        {
            InitializeComponent();

            CtrlAttendingDoctor.ItemsLines = Properties.Settings.Default.AttendingDoctorItems;
            CtrlMediastinus.ItemsLines = Properties.Settings.Default.MediastinusItems;
        }

        private void BtnClose_OnClick(object sender, System.Windows.RoutedEventArgs e)
        {
            RequestClose?.Invoke(this, EventArgs.Empty);
        }

        private void BtnSave_OnClick(object sender, System.Windows.RoutedEventArgs e)
        {
            RequestSave?.Invoke(this, EventArgs.Empty);
        }

        private bool AttendingDoctor_Save()
        {
            return SaveItems(CtrlAttendingDoctor, itemsText => Properties.Settings.Default.AttendingDoctorItems = itemsText);
        }

        private bool Mediastinus_Save()
        {
            return SaveItems(CtrlMediastinus, itemsText => Properties.Settings.Default.MediastinusItems = itemsText);
        }

        private bool SaveItems(ComboBoxSelectItemsEditUserControl ctrl, Action<string> setItemsText)
        {
            var itemsText = ComboBoxSelectItemsHelper.NormalizeItemsText(ctrl.ItemsLines);
            ctrl.ItemsLines = itemsText;
            setItemsText(itemsText);
            Properties.Settings.Default.Save();

            var name = ctrl.Name.Substring(4);
            var items = ComboBoxSelectItemsHelper.ToItemsArray(itemsText);
            KnownAppEvents.PublishComboBoxAutoCompleteItemsChanged(name, items);
            return true;
        }

        /// <inheritdoc />
        public bool CheckChanged()
        {
            return CtrlAttendingDoctor.CheckChanged() ||
                   CtrlMediastinus.CheckChanged();
        }

        /// <inheritdoc />
        public bool Save()
        {
            if (AttendingDoctor_Save())
            {
                CtrlAttendingDoctor.AcceptChanges();
            }

            if (Mediastinus_Save())
            {
                CtrlMediastinus.AcceptChanges();
            }

            return true;
        }

        /// <inheritdoc />
        public event EventHandler RequestClose;

        /// <inheritdoc />
        public event EventHandler RequestSave;
    }
}